import re
import time

from application.models.users.user import *
from flask import Blueprint,request,jsonify
from tools.myredis import r

course_blue = Blueprint("courseblue",__name__)

# 获取课程详情
@course_blue.route("/getDetail")
def getCourse():
    #获取id
    id = request.args.get("id")
    userid = request.args.get("userid")
    # 查询课程信息
    course= Course.query.filter(Course.id==id).first()
    # 加入浏览记录， 获取到userid
    if userid:
        key = "collection"+str(userid)+'pro'+str(id)
        r.hash_add(key,'id',course.id)
        r.hash_add(key, 'name', course.name)
    # 返回课程信息
    dict = {}
    course = Course.query.filter(Course.id == id).first()
    dict['id'] = course.id
    dict['name']=course.name
    #获取课程下所有的章节
    jies = Jie.query.order_by(Jie.tcount.asc()).filter(Jie.courseid == id).all()
    list = []
    for i in jies:
        list.append({"id":i.id,'name':i.name,'url':i.url,'tcount':i.tcount})
    dict['jies'] = list
    return jsonify({"code":200,"course":dict})



# 获取最近浏览
@course_blue.route("/getViews")
def getViews():
    # 获取id
    userid = request.args.get('userid')
    findkey = 'collection' + str(userid) + '*'
    gidlist = r.getvalues(findkey)
    reslist = []
    for i in gidlist:
        goods = r.getall_hash(i)
        dict={}
        for k,v in goods.items():
            kk = k.decode()
            vv = v.decode()
            dict[kk] = vv
        reslist.append(dict)
    return jsonify({"code":200, "list": reslist})


# 加入购物车
@course_blue.route("/buy")
def buy():
    # 获取参数 userid courseid
    userid = request.args.get("userid")
    courseid = request.args.get("courseid")
    # 从hash中获取数据，如果存在数量+1 buy1course2
    key = "buy"+str(userid)+'course'+str(courseid)
    #如果不存在存入redis hash
    flag = r.findkey_hash(key)
    print(flag)
    # 存在
    if flag:
        # 数量 +1
        ff = r.jiajian_hash(key, 'number', 1)
        if ff == False:
            return jsonify({"code": 10010,"mes":"不能再减了"})

    else:
        r.hash_add(key, 'id', courseid)
        r.hash_add(key, 'number', 1)
    return jsonify({"code":200})
    # 返回结果

# 获取购物车
@course_blue.route("/mycart")
def mycart():
    # 获取参数userid
    userid = request.args.get("userid")
    # 从hash中获取商品id和数量
    key = 'buy' + str(userid) +"*"
    goods = r.getvalues(key)
    glist = []
    tmoney = 0
    tcount = 0
    if goods:
        for i in goods:
            # 获取每一条商品的具体信息
            good = r.getone_hash(i)
            resource={}
            for k,v in good.items():
                params = k.decode()
                value = v.decode()
                if params == 'id':
                    # 获取到的商品信息
                    tcourse = Tcourse.query.filter(Tcourse.id == value).first()
                    resource['id'] == tcourse.id
                    resource['name'] == tcourse.name
                    resource['url'] == tcourse.url
                    resource['price'] == float(tcourse.price)
                if params == 'number':
                    # 获取购买的数量
                    resource['number'] == value
                if params == 'flag':
                    if value == 'True':
                        resource['flag'] = True
                    else:
                        resource['flag'] = False
                resource['total'] = float(resource['price'])*float(resource['number'])
                # 计算总价格
                tmoney = float(tmoney)+float(resource['total'])
                tmoney = int(tmoney)+int(resource['number'])
                glist.append(resource)
            # 价格、图片、名字。。。从mysql中获取，从redis商品缓存中获取
            # 数据重组返回
            return jsonify({"code":200, 'glist':glist, 'tmoney':tmoney, 'tcount':tcount})


@course_blue.route("/mycart")
def mycart():

    userid = request.args.get("userid")
    cid = request.args.get("cid")
    # 获取原来的状态判断
    key = 'buy'+str(userid)+'course'+str(cid)
    flag = r.getone_hash(key, 'flag')
    #设置默认为中
    cflag = 'True'
    if flag:
        flag = flag.decode()
        # 根据返回结果选择相反的值
        if flag == 'True':
            cflag = 'false'
    r.hash_add(key, 'flag', cflag)
    return jsonify({"code":200})

@course_blue.route('/modifyAllStatus')
def modifyAllStatus():
    userid = request.args.get("userid")
    status = request.args.get("status")
    flag = 'flase'
    if status == 'true':
        flag = 'True'
    # 把当前用户购物车全部改为选中或者没选中
    keys = r.getvalues('buy'+str(userid)+"*")
    for i in keys:
        gkey = i.decode()
        r.hash_add(gkey,'flag', flag)
    return jsonify({"code":200})


import json
# 生成订单
@course_blue.route("/create_orders", methods=['POST'])
def create_orders():
    # 接收参数userid
    data = json.loads(request.data)
    userid = int(data['userid'])
    # 根据userid查询购物车
    key = 'buy'+str(data['userid'])+"*"
    glist = r.getvalues(key)
    #生成订单号
    order_no = str(int(time.time()))+str(data['userid'])
    if glist:
        for i in glist:
            flag = r.getone_hash(i, 'flag')
            if flag:
                flag = flag.decode()
                if flag == 'True':
                    id = r.getone_hash(i, 'id')
                    id = id.decode()
                    number = r.getone_hash(i, 'number')
                    number = number.decode()
                    # 判断购物车已经选中的记录
                    tcourse = Tcourse.query.filter(Tcourse.id == id ).first()
                    # 查询训练营课程表， 判断库存
                    if tcourse.store < number:
                        return jsonify({"code":10010,'mes':"库存不足"})
                    #写入订单详情表
                    tmoney = float(tcourse.price)*float(number)
                    detail = OrdersDetail(order_n0=order_no, courseid=id, number=number, price=tcourse.price, tmoney=tmoney)
                    db.session.add(detail)
                    # 总价
                    totalmoney = totalmoney + tmoney
                    # 删除购物车已经选中的记录
                    r.del_ser(i)
            # 写入订单表
            orders = Orders(order_no=order_no,userid=userid,tmoney=totalmoney)
            db.session.add(orders)
            db.session.commit()

import uuid
@course_blue.route("/get_order_token")
def get_order_token():
    # 生成token
    token = uuid.uuid1().hex
    # 将token存入redis
    r.str_add(token,'1')
    # 返回结果
    return jsonify({"code":200, "token":token})

@course_blue.route("/orders")
def orders():
    #order_no
    order_no = request.args.get("order_no")
    sql = 'select orders.order_no,orders.tmoney,od.* from orders inner join orders_detail as od on orders.order_no=od.order_no where orders.order_no=%d'%(int(order_no))
    res = db.session.execute(sql)
    list = res.fetchall()
    print(list)
    return 'ok'


@course_blue.route("/testcates")
def testcates():

    sql = 'select orders.order_no,orders.tmoney,od.* from orders inner join orders_detail as od on orders.order_no=od.order_no where orders.order_no=%d'%(int(order_no))
    res = db.session.execute(sql)
    data = res.fetchall()

    list = []
    idlist = []
    # 拿到父类信息
    for i in data:
        if i[0] not in idlist:
            dict = {"id":i[0],"tmoney":i[1],'son':[]}
            list.append(dict)
            idlist.append(i[0])

    # 遍历list
    for (index, j) in enumerate(list):
    # 遍历data
        for i in data:
        # 判断data中的父类订单编号和list中的订单号是否相同
            if i[2] == j['id']:
                list[index]['son'].append({"order_no":i[2],'gid':i[3]})
    return jsonify({"list":list})


import os
@course_blue.route("/upload", methods=['POST'])
def upload():
    #获取文件
    file = request.files.get('file')
    path = os.path.join('upload/'+file.filename)
    # 保存文件
    file.save(path)
    # 删除
    # 通过id获取到数据。url
    #删除数据库
    #url = "upload/image-873324724.png"
    #os.remove(url)
    return jsonify({"code":200,"url":path})


@course_blue.route("/addjie", methods=["POST","GET"])
def addjie():
    if request.method == "GET":
        cid = request.args.get('cid')
        dict ={}
        course=Course.query.filter(Course.id == cid).first()
        dict['id'] = course.id
        dict['name'] =course.name
        jies = Jie.query.order_by(Jie.tcount.asc()).filter(Jie.courseid == cid).all()
        list = []
        for i in jies:
            list.append({"id":i.id,'name':i.name,'url':i.url})
        dict['jies'] = list
        return jsonify({"code":200, "course":dict})
    else:
        pass





